package top.jacktgq.itheima.netty.protocol_design.groupchat.server.example.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * @Author CandyWall
 * @Date 2021/3/23--14:49
 * @Description
 */
@Slf4j
public class EchoClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG)).addLast(new StringEncoder()).addLast(new StringDecoder())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        // ByteBuf byteBuf = (ByteBuf) msg;
                                        // log.debug("服务器端消息：{}", byteBuf.toString(Charset.defaultCharset()));
                                        log.debug("服务器端消息：{}", msg);
                                    }

                                    @Override
                                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                        log.debug("发生异常！");
                                        cause.printStackTrace();
                                    }
                                });
                    }
                })
                .connect("localhost", 8080);

        // 监听客户端连接事件
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("客户端连接成功... {}" + channelFuture.channel());
                // 监听客户端SocketChannel关闭事件，关闭客户端事件循环组中的事件循环
                Channel channel = channelFuture.channel();
                channel.closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // 客户端关闭
                        log.debug("客户端正在关闭...");
                        group.shutdownGracefully();
                        log.debug("客户端关闭成功！");
                    }
                });
                new Thread(() -> {
                    Scanner scanner = new Scanner(System.in);
                    String content = null;
                    do {
                        content = scanner.nextLine();
                        channel.writeAndFlush(content);
                    } while (!content.equals("close"));
                    // 如果用户输入了 close 就断开和服务器的channel连接
                    channel.close();
                }).start();
            }
        });

    }
}
